package app.Logic;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import app.Data.User;

public class UserAccounts implements Serializable{
	private ArrayList<User> accounts;
	private JFrame mainFrame;
	private User activeAccount = null;
	
	
	public UserAccounts(){}
	
	public boolean authenticate(String userName, String password){
		boolean result = false;
		for(int i = 0; i < accounts.size(); i++){
			if(accounts.get(i).getUserName().equals(userName)){
				if(accounts.get(i).getPassword().equals(password)){
					result = true;
				}
			}
		}
		
		return result;
	}
	
	public boolean checkUserName(String userName){
		boolean result = false;
		for(int i = 0; i < accounts.size(); i++){
			if(accounts.get(i).getUserName().equals(userName)){
				result = true;
			}
		}
		
		return result;
	}
	
	public boolean addUser(String userName, String password){
		if(!(checkUserName(userName))){
			User use = new User(userName, password);
			accounts.add(use);
			return true;
		}
		else
			return false;
	}
	
	public void saveAccounts(){
		try
		{
			FileOutputStream file = new FileOutputStream("./data/accounts.obj");
			ObjectOutputStream outStream = new ObjectOutputStream(file);
			outStream.writeObject(accounts);
		}
		catch(FileNotFoundException FNFE){
			System.out.println("FILE NOT FOUND EXCEPTION ERROR: Saving User Accounts");
		}
		catch(IOException IOE){
			System.out.println("IO EXCEPTION ERROR: Saving User Accounts");
		}
	}
	
	public void loadAccounts(){
		try
		{
			FileInputStream file = new FileInputStream("./data/accounts.obj");
			ObjectInputStream inStream = new ObjectInputStream(file);
			
			accounts = (ArrayList<User>) inStream.readObject();
		}
		catch(FileNotFoundException FFE)
		{
			accounts = new ArrayList<User>();
		}
		catch(IOException IOE){
			System.out.println("IO EXCEPTION ERROR: Loading User Accounts");
		}
		catch(ClassNotFoundException CNFE){
			System.out.println("CLASS NOT FOUND EXCEPTION ERROR: Loading User Accounts");
		}
	}
	
	public User getSingleAccount(String userName, String password){
		User use = null;
		for(int i = 0; i < accounts.size(); i++){
			if(accounts.get(i).getUserName().equals(userName)){
				if(accounts.get(i).getPassword().equals(password)){
					use = accounts.get(i);
				}
			}
		}
		return use;
	}
	
	public ArrayList<User> getAccounts(){return this.accounts;}
	public User getActiveUser(){return this.activeAccount;}
	public void setActiveUser(User use){this.activeAccount = use;}
}
